package controllers

import play.api._
import play.api.data._
import play.api.data.Forms._
import play.api.libs.json.Json
import play.api.mvc._
import play.api.db.slick._
import models._
import play.api.Play.current
import play.api.data.format.Formats._

import models.current.dao._
import models.current.dao.profile.simple._


//stable imports to use play.api.Play.current outside of objects:
import models.current.dao._
import models.current.dao.profile.simple._

object GoodController extends Controller{
  def index = DBAction { implicit rs =>
    Ok(views.html.good.index(GoodDB.Goods.list))
  }

  def list(page: Int, orderBy: Int, filter: String) = DBAction { implicit rs =>
    Ok(views.html.good.list(
      GoodDB.list(page = page, pageSize = 2, orderBy = orderBy, filter = ("%"+filter+"%")),
      orderBy, filter
    ))
  }

//  val goodForm = Form(
//    mapping(
//      "id" -> of[Long],
//      "name" -> text(),
//      "price" -> of[Double],
//      "cost" -> of[Double]
//    )(Good.apply)(Good.unapply)
//  )

//  val computerForm = Form(
//    mapping(
//      "id" -> optional(longNumber),
//      "name" -> nonEmptyText,
//      "introduced" -> optional(date("yyyy-MM-dd")),
//      "discontinued" -> optional(date("yyyy-MM-dd")),
//      "company" -> optional(longNumber)
//    )(Computer.apply)(Computer.unapply)
//  )

  val goodForm = Form(
    tuple(
      "name" -> nonEmptyText,
      "price" -> of[Double],
      "cost" -> of[Double]
    )
  )

  def insert = DBAction{ implicit rs =>
    goodForm.bindFromRequest.fold(
      errors => BadRequest,
      {
        case (name, price, cost) =>
          GoodDB.Goods.insert(Good(None, name, price, cost))
          Redirect(routes.GoodController.index)
      }
    )

//    val index = goodForm.bindFromRequest.get
//    Goods.insert(index)
//    Redirect(routes.GoodController.index)
  }

  implicit val goodReads = Json.reads[Good]
  implicit val goodWrites = Json.writes[Good]


  def listJson = DBAction { implicit rs =>
    //Goods.list
    Ok(Json.toJson(GoodDB.Goods.list))
  }
}
